<template>
  <div id="vxePulldownSelection">
    <vxe-pulldown :ref="'xDown4' + compId" transfer span="24" style="width: 100%">
      <template #default>
        <vxe-textarea class-name="width-100-percentage" class="enterNextInputFlag" v-model="keyvalue" autocomplete="off" auto-complete="new-password" :disabled="caUse" :readonly="isReadonly" suffix-icon="vxe-icon-num-list" placeholder="请选择" @keydown="enterConfirmEvent" @focus="focusEvent4" @blur="blurEvent4" @change="inputChange" @suffix-click="suffixClick4" @clear="clearConfirmEvent" clearable rows="1"></vxe-textarea>
      </template>
      <template #dropdown>
        <div class="my-dropdown4 radius round shadow-warp lines-orange solid" :style="{ width: panelWidth, height: panelHeight }">
          <vxe-grid :ref="'gridTable4' + compId" :auto-resize="true" border show-overflow height="auto" width="auto" :row-config="{ isHover: true, isCurrent: true }" :keyboard-config="{
            isArrow: true,
            isEnter: true,
            editMethodExmItem4
          }" :edit-config="{ mode: 'row' }" :column-config="{ resizable: false }" :loading="loading" :pager-config="isPage ? tablePage4 : null" :data="tableList" :columns="tableColumn" @cell-click="cellClickEvent4" @page-change="pageChangeEvent4"></vxe-grid>
        </div>
      </template>
    </vxe-pulldown>
    <!-- <span>这是组件</span> -->
  </div>
</template>
<script lang="ts" setup>
//#region  依赖注入
import { ref, reactive, getCurrentInstance, nextTick, onMounted, watch, defineProps } from 'vue';
import { pageSizes, IsEmpty, newGuid, sortByField } from '@/utils/common';

//#region  变量
let { proxy }: any = getCurrentInstance();
let a = reactive(pageSizes);
let b = ref(newGuid());
let compId: string = newGuid();
let keyvalue = ref('');
let caUse = ref(false);
let isReadonly = ref(false);
let loading = ref(false);
let tablePage4 = reactive({
  total: 0,
  currentPage: 1,
  pageSize: 200
});
let tableList = reactive([]);
//let tableColumn = reactive([]);
let totalCount = 0;

let selectedItem = {
  id: null,
  name: ''
};

// 父组件传值
let props = defineProps({
  url: String, //数据请求地址
  requestType: { type: String, default: 'get' }, //请求方式
  tableColumn: Array as () => String[], //列集合
  displayTexts: Array as () => String[], //显示字段集合
  displayTextObj: String, //显示字段集合
  dataObj: {}, //接口参数。{key1:value1,key2:value2...}
  isDisabled: Boolean, //是否可用
  isReadonly: Boolean, //是否只读
  isChild: Boolean, //是否子行
  childIndex: Number, //子航索引
  aimKeys: { type: Array as () => String[], default: [] }, //目标字段
  resItem: String, //返回数据中，包含所需数据的名称
  isChangeName: Boolean, //输入框内容是否可手动更改
  compName: String, //组件名称
  dataName: String, //请求数据结构名称
  isRow: Boolean,
  rowIndex: String,
  panelWidth: { type: String, default: '450px' },
  panelHeight: { type: String, default: '300px' },
  isPage: { type: Boolean, default: false }, //是否需要分页
}) as any;

watch(
  () => props.displayTextObj,
  (n, o) => {
    keyvalue.value = n;
    if (!tableList || tableList.length <= 0) {
      findList();
    }
  },
  {
    deep: true,
    immediate: true
  }
);
watch(
  () => props.baseList,
  (newval, oldvbal) => {
    /*keyvalue.value = newval;*/
    //console.log(3333,newval)
  },
  {
    deep: true,
    immediate: true
  }
);

watch(
  () => props.isDisabled,
  (newval, oldvbal) => {
    caUse.value = newval;
  },
  {
    deep: true,
    immediate: true
  }
);

//#region  计算属性
// const inputText = ref computed(() => {
//   console.log(props.displayTextObj);
//   const aim = tableList.filter(p => p.code === keyvalue.value || p.name === keyvalue.value);
//   if (aim && aim.length > 0) {
//     return aim[0].name;
//   }
//   return props.displayTextObj;
// });

//#endregion

//#endregion

//#region  属性

//#endregion

//#region  监听器

//#endregion

//#endregion

//#region  生命周期函数
onMounted(() => {
  //todo
});
//#endregion

//#region  函数
function findList() {
  loading.value = true;
  tableList.length = 0;
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    return;
  }

  let url = proxy.url;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim().toUpperCase(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
  };
  // 循环父组件传来的特殊查询字段，添加到data上
  if (!IsEmpty(proxy.dataObj)) {
    for (const key in proxy.dataObj) {
      if (proxy.dataObj[key]) {
        data[key] = proxy.dataObj[key];
      }
    }
  }
  if (proxy.requestType === 'post') {
    proxy.$http
      .post(url, data)
      .then((res: any) => {
        tableList.push(...sortByField(res.data, 'sx'));
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  } else {
    proxy.$http
      .get(url, { params: data })
      .then((res: any) => {
        tableList.push(...res.data);
        loading.value = false;
        proxy.$nextTick(() => {
          const $xTable = proxy.$refs['gridTable4' + compId] as any;
          if ($xTable) {
            $xTable.focus();
            if (tableList.length > 0) {
              $xTable.setCurrentRow(tableList[0]);
            }
          }
        });
      })
      .catch((err: any) => {
        loading.value = false;
      });
  }
}

// 获取列表
function findListWithUrl(pUrl: string) {
  if (IsEmpty(pUrl)) {
    tableList = [];
    return;
  }
  //#region  判断请求接口地址为空
  if (IsEmpty(proxy.url)) {
    loading.value = false;
    tableList = [];
    return;
  }
  //#endregion
  let url = pUrl;
  let data: any = {
    filter: IsEmpty(selectedItem.name) ? null : selectedItem.name.toString().trim(),
    sorting: null,
    skipCount: (tablePage4.currentPage - 1) * tablePage4.pageSize,
    maxResultCount: tablePage4.pageSize
  };
  proxy.$http
    .get(url, { params: data })
    .then((res: any) => {
      tableList = res.data; //.push(...res.data);
      tablePage4.total = res.totalCount;
      loading.value = false;
    })
    .catch((err: any) => {
      //loading = false;
      //.$alert(err.data.error.message, '提示');
    });
}

//回车选中
function enterConfirmEvent({ value, $event }) {
  if ($event && ($event.keyCode === 13 || $event.keyCode === 9)) {
    const $xDown4 = proxy.$refs['xDown4' + compId] as any;
    if ($xDown4.isPanelVisible()) {
      const $xTable = proxy.$refs['gridTable4' + compId] as any;
      const rowSelect = $xTable.getCurrentRecord();
      cellClickEvent4({ row: rowSelect });
    }
  }
}

// 获取焦点
function focusEvent4() {
  findList();
  const $xDown = proxy.$refs['xDown4' + compId] as any;
  $xDown.showPanel();
  proxy.$nextTick(() => {
    const $xTable = proxy.$refs['gridTable4' + compId] as any;
    $xTable.focus();
    if (tableList.length > 0) {
      $xTable.setCurrentRow(tableList[0]);
    }
  });
}
// 失去焦点
function blurEvent4({ value }) {
  // 输入框内容未改变
  if (value === proxy.displayTextObj) {
    return;
  }
  proxy.$emit('confirmClick', value);
}
function inputChange(e) {
  //todo
}
// 值改变  1  男，2  女
// function inputChange(e) {
//   const $xDown = proxy.$refs['xDown4' + compId] as any;
//   $xDown.hidePanel();
//   keyvalue.value = '';
//   setTimeout(() => {
//     keyvalue.value = e.value;
//     proxy.$emit('confirmClick', {
//       isChild: props.isChild,
//       childIndex: props.childIndex,
//       row: { ...b, entity: b },
//       aimKeys: props.aimKeys,
//     });

//   }, 50);
// }

function keyupEvent4() {
  const $xTable = proxy.$refs['xDown4' + compId] as any;
  $xTable.showPanel();
}

function suffixClick4() {
  const $xDown = proxy.$refs['xDown4' + compId] as any;
  $xDown.togglePanel();
}
// 清空
function clearConfirmEvent() {
  //todo
  proxy.$emit('confirmClick', {
    isChild: proxy.isChild,
    childIndex: proxy.childIndex,
    row: { ...{ id: null }, entity: { id: null } },
    aimKeys: proxy.aimKeys,
    compName: proxy.compName
  });
}
function editMethodExmItem4() {
  //todo
}
//行选中
function cellClickEvent4({ row }) {
  const $xDown = proxy.$refs['xDown4' + compId] as any;
  if (IsEmpty(row)) {
    $xDown.hidePanel();
    return;
  }
  keyvalue.value = row.name;
  proxy.$emit('confirmClick', keyvalue.value);
  $xDown.hidePanel();
}
function pageChangeEvent4({ type, currentPage, pageSize }) {
  tablePage4.currentPage = currentPage;
  tablePage4.pageSize = pageSize;
  findList();
}
function selectRow() {
  (proxy.$refs.table as any).setCurrentRow(proxy.tableList[0]);
}
//#endregion
</script>
<style lang="scss" scoped>
#vxePulldownSelection {
  :deep(.my-dropdown4) {
    padding: 4px;
    min-width: 400px;
    height: 450px;
    background-color: #fff;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
    cursor: pointer;
  }

  :deep(.vxe-pager.size--mini) {
    height: 33px !important;
  }
}
</style>
